﻿using System;
using System.Collections.Generic;
using System.Linq;
using Innovative.DateTimeInterval;

namespace Innovative.Atom.Timer.Event
{
	public class AtomScheduledTimesEvent : AtomEvent
	{
		private List<IDateTimeInterval> _timeList = new List<IDateTimeInterval>();

		public AtomScheduledTimesEvent(IDateTimeInterval interval)
		{
			_timeList.Add(interval);
		}

		public AtomScheduledTimesEvent(IEnumerable<IDateTimeInterval> intervalList)
		{
			if (intervalList.Count() > 0)
			{
				_timeList.AddRange(intervalList);
			}
			else
			{
				throw new ArgumentException("There must be at least one interval specified.", "intervalList");
			}
		}

		internal List<IDateTimeInterval> IntervalList
		{
			get
			{
				return _timeList;
			}
			set
			{
				_timeList = value;
			}
		}

		protected override void OnInitializeNextEventDateTime()
		{
			// ***
			// *** Order the times oldest to newest
			// ***
			var qry = from tbl in this.IntervalList
					  orderby tbl.NextDateTime ascending
					  select tbl;

			// ***
			// *** There will always be at least one time
			// ***
			this.EventDateTime = qry.First().NextDateTime;
		}

		protected override void OnUpdateNextEventDateTime()
		{
			// ***
			// *** Order the times oldest to newest
			// ***
			var qry = from tbl in this.IntervalList
					  orderby tbl.NextDateTime ascending
					  select tbl;

			// ***
			// *** There will always be at least one time
			// ***
			this.EventDateTime = qry.First().NextDateTime;
		}
	}
}
